package com.example.highclasscomponent.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.highclasscomponent.R;
import com.example.highclasscomponent.pojo.Planet;

import java.util.List;

public class PlanetBaseAdapter_withButton extends BaseAdapter {
    private Context context;
    private List<Planet> mPlanetList;

    public PlanetBaseAdapter_withButton(Context context, List<Planet> mPlanetList) {
        this.context = context;
        this.mPlanetList = mPlanetList;
    }

    //返回列表项的个数
    @Override
    public int getCount() {
        return mPlanetList.size();
    }

    @Override
    public Object getItem(int position) {
        return mPlanetList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    //返回每一项的布局
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if(convertView==null) {
            viewHolder=new ViewHolder();
            //根据布局文件Item.xml生成转换视图对象
            convertView = LayoutInflater.from(context).inflate(R.layout.item_list_with_button, null);
            viewHolder.iv_icon = convertView.findViewById(R.id.iv_icon);
            viewHolder.tv_name = convertView.findViewById(R.id.tv_name);
            viewHolder.tv_desc = convertView.findViewById(R.id.tv_desc);
            viewHolder.btn=convertView.findViewById(R.id.btn);
            convertView.setTag(viewHolder);
        }
        else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        //给控件设置好数据
        Planet planet = mPlanetList.get(position);
        viewHolder.iv_icon.setImageResource(planet.image);
        viewHolder.tv_name.setText(planet.name);
        viewHolder.tv_desc.setText(planet.desc);
        viewHolder.btn.setOnClickListener(v->{
            Toast.makeText(context, "按钮被点击了", Toast.LENGTH_SHORT).show();
        });
        return convertView;
    }

    public final class ViewHolder {
        ImageView iv_icon;
        TextView tv_name;
        TextView tv_desc;
        Button btn;
    }

}
